const userId = new Date().getTime().toString(36);   // 时间戳转三十六进制方式生成唯一编号，如：lswte2aq
var ws = new WebSocket(`ws://192.168.2.156:8081/${userId}`);

ws.onopen = (ev) => {
    console.log(`websocket onopen`);
}

ws.onmessage = (ev) => {
    console.log(`websocket onmessage: ${ev.data}`);

    var mes = JSON.parse(ev.data);
    appendRecord(mes.data, mes.type, mes.sender);
}

ws.onclose = (ev) => {
    console.log(`websocket onclose: ${ev}`);
}

ws.onerror = (ev) => {
    console.log(`websocket onerror: ${ev}`);
}

// 发送按钮点击后的处理
document.getElementById('btnSend').onclick = (ev) => {
    let txtMessage = document.getElementById('txtMessage');
    ws.send(`${txtMessage.value}`);
};

// 每次收到消息后，把消息展示在一个新的div中
function appendRecord(message, type, sender){
    var div = document.createElement("div");
    div.innerHTML = message;
    div.style.marginTop = "10px";

    switch(type){
        case "enter":
            // div.style.color = "blue";
            div.className = "record-join";
            break;
        case "leave":
            // div.style.color = "red";
            div.className = "record-leave";
            break;
        case "message":
            div.className = userId == sender ? "record-send" : "record-receive";            
            if(userId == sender){
                div.innerHTML += `<span class="face">${sender}</span>`
            }else{                            
                div.innerHTML = `<span class="face">${sender}</span>` + div.innerHTML;
            }
            break;
    }
    
    document.getElementById('record').appendChild(div);
}